package meb

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log/slog"
    "vitepress-serve/internal/common/hgin"
    "vitepress-serve/internal/model"
)

// Shared constant for the entire package
const ctxHostKey = "ctx_host_uid_"

type ProductListBody struct {
    Items []ProductListBodyItem `json:"items"`
}

type ProductListBodyItem struct {
    ProdId    string `json:"prodId"`
    ProdName  string `json:"prodName"`
    UnitPrice uint64 `json:"unitPrice"`
    MarkPrice uint64 `json:"markPrice"`
    Intro     string `json:"intro"`
    Thumb     string `json:"thumb"`
    Type      string `json:"type"`
}

// ProductList 产品列表
func (ctl *Controller) ProductList(ctx *gin.Context) (err error) {
    slog.Info("开始获取商品列表",
        "path", ctx.Request.URL.Path,
        "method", ctx.Request.Method,
        "client_ip", ctx.ClientIP(),
    )

    var products []model.Product
    if err = ctl.db.Where("status = ?", model.ProductStatus_UP).Order("rank DESC").Find(&products).Error; err != nil {
        slog.Error("查询商品列表失败", 
            "error", err,
            "sql", ctl.db.Statement.SQL.String(),
        )
        return fmt.Errorf("查询商品列表失败: %w", err)
    }

    slog.Info("查询商品列表完成", 
        "products_count", len(products),
        "status_filter", model.ProductStatus_UP,
    )

    // 添加空数据判断
    if len(products) == 0 {
        slog.Info("未找到可用商品")
        hgin.ApiRes(ctx, gin.H{
            "status": "1",
            "data": ProductListBody{
                Items: []ProductListBodyItem{},
            },
            "message": "暂无可用商品",
        })
        return nil
    }

    var items = make([]ProductListBodyItem, 0)
    for _, p := range products {
        items = append(items, ProductListBodyItem{
            ProdId:    p.ProdId,    // 保持与数据库字段名一致
            ProdName:  p.ProdName,   // 保持与数据库字段名一致
            UnitPrice: p.UnitPrice,
            MarkPrice: p.MarkPrice,
            Intro:     p.Intro,
            Thumb:     p.Thumb,
            Type:      string(p.Type),
        })
    }

    hgin.ApiRes(ctx, gin.H{
        "status": "1",
        "data": ProductListBody{
            Items: items,
        },
    })
    return nil
}
